//
//  DetailViewController.m
//  FMDB-名片
//
//  Created by Hello Cai on 16/2/18.
//  Copyright © 2016年 Hello Cai. All rights reserved.
//

#import "DetailViewController.h"
#import "Person.h"
#import "DataBaseManager.h"
@interface DetailViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (weak, nonatomic) IBOutlet UITextField *nameTF;

@property (weak, nonatomic) IBOutlet UITextField *phoneTF;

@property (weak, nonatomic) IBOutlet UIImageView *showImage;
@end

@implementation DetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    if (self.personModel) {
        self.nameTF.text = self.personModel.nameStr;
        self.phoneTF.text = self.personModel.phoneStr;
        self.showImage.image = [UIImage imageWithData:self.personModel.imageData];
    }
}

- (IBAction)setImageBtnClicked:(id)sender {
    //打开相册
    UIImagePickerController *pickCtl = [UIImagePickerController new];
    pickCtl.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    pickCtl.delegate = self;
    [self presentViewController:pickCtl animated:YES completion:nil];
}

- (IBAction)sureBtnClicked:(id)sender {
    //过滤空数据
    if(self.nameTF.text.length!=0 && self.phoneTF.text.length!=0 && self.showImage.image!=nil){
        Person *perModel = [Person new];
        perModel.nameStr = self.nameTF.text;
        perModel.phoneStr = self.phoneTF.text;
        perModel.imageData = UIImageJPEGRepresentation(self.showImage.image, 1.0);
        
        if (self.personModel) {
            [[DataBaseManager shareDatabase] updatePerson:perModel oldModel:self.personModel];
        }else{
            //保存数据
            [[DataBaseManager shareDatabase] insertPersonModel:perModel];
        }
        
        //回到列表界面
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        //出错提醒
        UIAlertView *alerView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"数据有误" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alerView show];
    }
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    //把选择的图片展示到界面上
    self.showImage.image = info[@"UIImagePickerControllerOriginalImage"];
    
    //在相册中选择完图片后关闭相册
    [picker dismissViewControllerAnimated:YES completion:nil];
}

@end
